package com.wujilee.wujileenetty.demos.web.wechat;

import com.fasterxml.jackson.annotation.JsonSubTypes;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;

/**
 * @author liwuji
 * @date 2024/7/30
 * @desc
 **/
public class Service {
    private static Selector selector;
    private static ServerSocketChannel socketChannel;
    private static  int PORT = 6666;

    public static void main(String[] args) throws IOException {

        selector = Selector.open();
        socketChannel = ServerSocketChannel.open();
        socketChannel.socket().bind(new InetSocketAddress(PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
    public static void  list() throws IOException {


        while (true){
            int select = selector.select(200);
            if(select> 0){
                selector.selectedKeys().stream().forEach(selectionKey -> {
                    try {

                        if(selectionKey.isAcceptable()){
                                SocketChannel accept = socketChannel.accept();
                                accept.register(selector,SelectionKey.OP_READ);
                                System.out.println(accept.getRemoteAddress() +"上线了");
                        }
                        if(selectionKey.isReadable()){

                        }

                    }catch (Exception e){

                    }

                });
            }
        }

    }
    private static  void read(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read = channel.read(buffer);
        if(read != -1){
            String str = new String(buffer.array());
            System.out.println(" from 客户端 "+str);
        }
    }
    private static  void forward(String msg,SocketChannel channel ){
        System.out.println("服务器转发消息");
        selector.keys().stream().forEach(selectionKey -> {
            try {

                SelectableChannel channel1 = selectionKey.channel();
                if(!channel1.equals(channel1)){
                    ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                    channel.write(wrap);
                }
            }catch (Exception e){
                throw new RuntimeException(e);
            }

        });

    }


}
